/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.social.showcase.signin;

import javax.inject.Inject;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.showcase.service.account.Account;
import org.springframework.social.showcase.service.account.AccountRepository;
import org.springframework.social.showcase.service.account.UsernameAlreadyInUseException;
import org.springframework.social.showcase.signup.SignupController;
import org.springframework.social.showcase.signup.SignupForm;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;

@Controller
public class SigninController {

	private final AccountRepository accountRepository;
	private final static Log logger = LogFactory.getLog(SigninController.class);
	
	@Inject
	public SigninController(AccountRepository accountRepository) {
		this.accountRepository = accountRepository;
	}
	@RequestMapping(value="/signin", method=RequestMethod.GET)
	public SigninForm signin(WebRequest request) {
		return new SigninForm();
		
	}
	
	@RequestMapping(value="/signin", method=RequestMethod.POST)
	public String signin(@Valid SigninForm form, BindingResult formBinding, WebRequest request) {
		System.out.println("/signin/authenticate");
		if (formBinding.hasErrors()) {
			return null;
		}
		Account account = validateAccount(form, formBinding);
		if (account != null) {
			SignInUtils.signin(account.getUsername());
			ProviderSignInUtils.handlePostSignUp(account.getUsername(), request);
			return "redirect:/";
		}
		return null;
	}
	
	private Account validateAccount(SigninForm form, BindingResult formBinding) {
			Account account=accountRepository.findAccountByUsername(form.getUsername());
			return account;
		
	}
}
